// BY BC Chong


/// <reference name="MicrosoftAjaxTimer.debug.js" />
/// <reference name="MicrosoftAjaxWebForms.debug.js" />
/// <reference name="Sys.Extended.UI.ExtenderBase.BaseScripts.js" assembly="AjaxControlToolkit" />


Type.registerNamespace('AjaxControlToolkitEx');

AjaxControlToolkitEx.TopMostPanelExtenderBehavior = function(element) {
    AjaxControlToolkitEx.TopMostPanelExtenderBehavior.initializeBase(this, [element]);

    this._hiddenFieldID = null;
    this._disableOnPostBack = false;
    
    
    this._targetClickDelegate = null;
    this._bodyclickDelegate = null;
    this._bodykeydownDelegate = null;
    this._focusDelegate = null;
    this._blurDelegate = null;
        
    this._isPnlClicked = false;        
            
    this._timer = null;
    this._tickHandler = null;
}

AjaxControlToolkitEx.TopMostPanelExtenderBehavior.prototype = {
    initialize : function() {
        AjaxControlToolkitEx.TopMostPanelExtenderBehavior.callBaseMethod(this, 'initialize');

        var pnl = this.get_element();
        var hf = $get(this.get_HiddenFieldID());

        pnl.style.position = 'absolute';
        pnl.style.position = 'fixed';
        //pnl.style.display = 'none';
        
        pnl.setAttribute("TopMostPanel","1");

        if (!pnl.tabIndex) pnl.tabIndex = 0;


        if (this._focusDelegate === null) {
            this._focusDelegate = Function.createDelegate(this, this._focusHandler);
        }
        Sys.UI.DomEvent.addHandler(pnl, 'focus', this._focusDelegate);

        if (this._blurDelegate === null) {
            this._blurDelegate = Function.createDelegate(this, this._blurHandler);
        }
        Sys.UI.DomEvent.addHandler(pnl, 'blur', this._blurDelegate);

        if (this._targetClickDelegate === null) {
            this._targetClickDelegate = Function.createDelegate(this, this._targetClickHandler);
        }
        Sys.UI.DomEvent.addHandler(pnl, 'click', this._targetClickDelegate);

        if (this._bodyclickDelegate === null) {
            this._bodyclickDelegate = Function.createDelegate(this, this._bodyclickHandler);
        }
        $addHandler(document, 'click', this._bodyclickDelegate);
                
        if (this._bodykeydownDelegate == null) {
            this._bodykeydownDelegate = Function.createDelegate(this, this._bodykeydownHandler);
        }
        $addHandler(document, 'keydown', this._bodykeydownDelegate);

		
		if (hf!=null){
            if (hf.value != '1')
                this.hide();
            else
                this.show();
        }
		
        if (!this._tickHandler) {
            this._tickHandler = Function.createDelegate(this, this._onTimerTick);
        }
						
		this.registerPartialUpdateEvents();
    },

    dispose : function() {
        
        var pnl = this.get_element();
        var hf = $get(this.get_HiddenFieldID());

        if (this._focusDelegate) {
            Sys.UI.DomEvent.removeHandler(pnl, 'focus', this._focusDelegate);            
            delete this._focusDelegate;
        }
        if (this._blurDelegate) {
            Sys.UI.DomEvent.removeHandler(pnl, 'blur', this._blurDelegate);            
            delete this._blurDelegate;
        }
        if (this._targetClickDelegate) {
            Sys.UI.DomEvent.removeHandler(pnl, 'click', this._targetClickDelegate);            
            delete this._targetClickDelegate;
        }
        
        if (this._bodyclickDelegate) {
            Sys.UI.DomEvent.removeHandler(document, 'click', this._bodyclickDelegate);
            delete this._bodyclickDelegate;
        }

        if (this._bodykeydownDelegate) {
            Sys.UI.DomEvent.removeHandler(document, 'keydown', this._bodykeydownDelegate);
            delete this._bodykeydownDelegate;
        }
        
        if (this._timer) {
            this._timer.dispose();
            this._timer = null;
        }
        if (this._tickHandler){
			delete this._tickHandler;
			this._tickHandler = null;
		}
		
		
        AjaxControlToolkitEx.TopMostPanelExtenderBehavior.callBaseMethod(this, 'dispose');
    },

    _partialUpdateBeginRequest : function(sender, beginRequestEventArgs) {
        /// <param name="sender" type="Object">
        /// Sender
        /// </param>
        /// <param name="beginRequestEventArgs" type="Sys.WebForms.BeginRequestEventArgs">
        /// Event arguments
        /// </param>
        AjaxControlToolkitEx.TopMostPanelExtenderBehavior.callBaseMethod(this, '_partialUpdateBeginRequest', [sender, beginRequestEventArgs]);

		if (this._timer == null){
			this._timer = new Sys.Timer();
			this._timer.add_tick(this._tickHandler);
			this._timer.set_interval(100);
			this._timer.set_enabled(true);
		}
        
    },

    _partialUpdateEndRequest : function(sender, endRequestEventArgs) {
        /// <param name="sender" type="Object">
        /// Sender
        /// </param>
        /// <param name="endRequestEventArgs" type="Sys.WebForms.EndRequestEventArgs">
        /// Event arguments
        /// </param>
        AjaxControlToolkitEx.TopMostPanelExtenderBehavior.callBaseMethod(this, '_partialUpdateEndRequest', [sender, endRequestEventArgs]);

        if (this._timer) {
            this._timer.dispose();
            this._timer = null;
        }

        if (this.get_element()){
            // Look up result by element's ID
            var action = endRequestEventArgs.get_dataItems()[this.get_element().id];
            if ("show" == action) {
                this.show();
            } else if ("hide" == action) {
                this.hide();
            }
        }
    },
    
    get_HiddenFieldID : function() {
        /// <value type="String">
        /// The ID of the control to display
        /// </value>
        return this._hiddenFieldID;
    },
    set_HiddenFieldID : function(value) {
        if (this._hiddenFieldID != value) { 
            this._hiddenFieldID = value;
            this.raisePropertyChanged('HiddenFieldID');
        }
    },

    get_DisableOnPostBack : function() {
        return this._disableOnPostBack;
    },
    set_DisableOnPostBack : function(value) {
        if (this._disableOnPostBack != value) { 
            this._disableOnPostBack = value;
            this.raisePropertyChanged('DisableOnPostBack');
        }
    },        
        
    
    show: function() {
        var pnl = this.get_element();
        var hf = $get(this.get_HiddenFieldID());
        
        var clientBounds = $common.getClientBounds();
        var clientWidth = clientBounds.width;
        var clientHeight = clientBounds.height;
        /*
        var sz = $common.getSize(document.body);
        sz.width = clientWidth - 30;
        sz.height = clientHeight - 30;
        $common.setSize(document.body, sz);
        */  
        var newlypopup = false;    
        if (pnl != null && hf !=null){
			if (pnl.style.display == '' || 
				pnl.style.display == 'none')
				newlypopup = true;
            pnl.style.display = 'block';       
            hf.value = '1';
            //pnl.focus();
        }
        //if (newlypopup){
			this.position();
		//}
    },
    
    hide: function() {
    
        var pnl = this.get_element();
        var hf = $get(this.get_HiddenFieldID());
    
        if (pnl != null && hf !=null){
            pnl.style.display = 'none';       
            hf.value = '0';
        }
    },
            
        
    _onTimerTick : function() {
		//this._timer.set_enabled(false);
			//var pnl = this.get_element();
			//pnl.style.display = 'none'; 
			//this.bringToFront(pnl.id);  
		this.position();        
			//pnl.style.display = 'block';   
		//this._timer.set_enabled(true);
    },
        /*
	getAbsoluteDivs: function()   
	{   
		var arr = new Array();   
		var all_divs = document.body.getElementsByTagName("DIV");   
		var j = 0;   
	  
		for (i = 0; i < all_divs.length; i++)   
			if (all_divs.item(i).style.position=='absolute')   
			{   
				arr[j] = all_divs.item(i);   
				j++;   
			}   
	  
		return arr;   
	},
	  
	bringToFront: function (id)   
	{   
		if (!document.getElementById ||   
			!document.getElementsByTagName)   
			return;   
	  
		var obj = $get(id);   
		var divs = this.getAbsoluteDivs();   
		var max_index = 0;   
		var cur_index;   
	  
		// Compute the maximal z-index of   
		// other absolute-positioned divs   
		for (i = 0; i < divs.length; i++)   
		{   
			var item = divs[i];   
			if (item == obj ||   
				item.style.zIndex == '')   
				continue;   
	  
			cur_index = parseInt(item.style.zIndex);   
			if (max_index < cur_index)   
			{   
				max_index = cur_index;   
			}   
		}   
	  
		obj.style.zIndex = max_index + 1;   
		delete divs;
	},
	
	sendToBack: function(id)   
	{   
		if (!document.getElementById ||   
			!document.getElementsByTagName)   
			return;   
	  
		var obj = document.getElementById(id);   
		var divs = getAbsoluteDivs();   
		var min_index = 999999;   
		var cur_index;   
	  
		if (divs.length < 2)   {
		delete divs;
			return;   
			}
	  
		// Compute the minimal z-index of   
		// other absolute-positioned divs   
		for (i = 0; i < divs.length; i++)   
		{   
			var item = divs[i];   
			if (item == obj)   
				continue;   
	  
			if (item.style.zIndex == '')   
			{   
				min_index = 0;   
				break;   
			}   
	  
			cur_index = parseInt(item.style.zIndex);   
			if (min_index > cur_index)   
			{   
				min_index = cur_index;   
			}   
	  
		}   
	  
		if (min_index > parseInt(obj.style.zIndex))   
		{   
			delete divs;
			return;   
		}   
	  
		obj.style.zIndex = 1;   
	  
		if (min_index > 1)  { 
			delete divs;
			return;   
			}
	  
		var add = min_index == 0 ? 2 : 1;   
	  
		for (i = 0; i < divs.length; i++)   
		{   
			var item = divs[i];   
			if (item == obj)   
				continue;   
	  
			item.style.zIndex += add;   
		}   
		delete divs;
	},   
	
       */
    position: function(dx,dy) {
		if (this.get_DisableOnPostBack()) {
			var status = Sys.WebForms.PageRequestManager.getInstance().get_isInAsyncPostBack();
			if (status)
				return;
		}
		
		
        var pnl = this.get_element();
        var hf = $get(this.get_HiddenFieldID());
       
    
        if (pnl != null){
			if (pnl.parentNode.style.display == 'none')
				return;

            //var all = document.all || document.getElementsByTagName("body")[0].getElementsByTagName("*");
            var all = document.all || document.getElementsByTagName('*'); 
            var zindex = parseInt(pnl.style.zIndex);
                        
            for(var i=0, ne; ne=all[i++];) {
				var isTopMost = ne.getAttribute("TopMostPanel");
                if ( pnl != ne
                    && parseInt(zindex) <= parseInt(ne.style.zIndex)
                    && isTopMost != "1"){
                     zindex = parseInt(ne.style.zIndex) + 1;
                     }
            }
            if (parseInt(zindex) > parseInt(pnl.style.zIndex)){
                pnl.style.zIndex = parseInt(zindex);
            }            
            
            
		/*
			var scrollX = 0;
			var scrollY = 0;
             	        
			if (document.documentElement && document.documentElement.scrollTop) {
				scrollX = document.documentElement.scrollLeft;
				scrollY = document.documentElement.scrollTop;
			} else {
				scrollX = document.body.scrollLeft;
				scrollY = document.body.scrollTop;
			}
			
			
			var x = 0;
			var y = 0;
			              
			var clientBounds = $common.getClientBounds();
			var width = clientBounds.width;
			var height = clientBounds.height;
	        
			x = Math.max(0, Math.floor(x + width / 2.0 - pnl.offsetWidth / 2.0));
			y = Math.max(0, Math.floor(y + height / 2.0 - pnl.offsetHeight / 2.0));            

            var offsetY = 0, offsetX = 0;
            var pe = pnl.parentNode;
            while(pe!=null && pe.nodeName.toLowerCase() != 'form'){
                if (pe.style != null && pe.style.position == 'absolute' 
					//&& pe.style.position == 'fixed' 
                    && pe.style.display != 'none'){
                    offsetY = Sys.UI.DomElement.getLocation(pe).y;
                    offsetX = Sys.UI.DomElement.getLocation(pe).x;
                    break;
                }
                pe = pe.parentNode;
            }

            Sys.UI.DomElement.setLocation(pnl, x - offsetX + scrollX, y - offsetY + scrollY);
        */
        }        
    },
    
    
    
    _focusHandler: function(event) {
    },
    _blurHandler: function(event) {
        if (this._isPnlClicked){
            //this.get_element().focus();
        }
    },
    _targetClickHandler: function(event) {
        this._isPnlClicked = true;
    },
    _bodyclickHandler: function(event) {
        if (this._isPnlClicked){
            this._isPnlClicked = false;            
        }else{
			//this.hide();
			//event.stopPropagation();     
			//event.preventDefault();						
        }
    },
    _bodykeydownHandler: function(event) {
    
        if (event.keyCode == 27 /* Escape */) {
            //this.hide();            
        }
    }

    
    
}
AjaxControlToolkitEx.TopMostPanelExtenderBehavior.registerClass('AjaxControlToolkitEx.TopMostPanelExtenderBehavior', Sys.Extended.UI.BehaviorBase);
